package com.mew.chess.core.game.qmcs.game;

import cn.hutool.core.util.RandomUtil;
import com.mew.chess.core.game.qmcs.game.common.*;
import com.mew.chess.core.game.shbz.game.common.FishTableLog;
import com.mew.common.rest.bo.GameSession;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@Data
@ToString(of = {"roomId", "tableId"})
@NoArgsConstructor
@EqualsAndHashCode(of = {"roomId", "tableId"})
public class QmcsTableManager {
    private static final Logger logger = LoggerFactory.getLogger(QmcsTableManager.class);
    private int roomId;
    private int roomType;
    private int tableId;

    private int linkType;
    private long startTime;
    private int ruleTime;
    private AtomicInteger fishKeyId = new AtomicInteger(0);

    private final ConcurrentMap<Long, QmcsUserBO> onlineUserMap = new ConcurrentHashMap<>(16); //userId   v: seatNo
    private final ConcurrentMap<Integer, QmcsSeatManager> seatMap = new ConcurrentHashMap<>(16); //userId v seatmanager
    private final ConcurrentMap<Integer, QmcsBO> qmcsMap = new ConcurrentHashMap<>(16); //seaNo userId

    private QmcsScheduleManager qmcsScheduleManager;
    private final Semaphore semaphore = new Semaphore(1);

    //记录
    public long logTime;
    public long playTimes;
    public long dodgeTimes;
    public HashMap<Integer, FishTableLog> logMap = new HashMap<>();  //押注  鱼

    public QmcsTableManager(int roomId, int roomType, int tableId){
        this.roomId = roomId;
        this.roomType = roomType;
        this.tableId = tableId;
        this.qmcsScheduleManager = new QmcsScheduleManager(tableId,roomId);
    }

    public boolean checkIsNoStart() {
        return qmcsScheduleManager.getFlag().get();
    }

    public void startGame(){
        qmcsScheduleManager.start();
    }

    public void sitDown(QmcsSeatManager seatManager){
        seatMap.put(seatManager.getSeatNo(), seatManager);
    }

    public void standUP(int seatNo){
        seatMap.remove(seatNo);
    }

    public void pushOnlineUserMap(QmcsUserBO qmcsUserBO){

        onlineUserMap.put(qmcsUserBO.getUserId(), qmcsUserBO);
        QmcsTableUtil.playerInoutMsg(this, seatMap.get(qmcsUserBO.getSeatNo()), 1);
    }

    public QmcsSeatManager getSeatByUserId(long userId){
        if (null==onlineUserMap.get(userId)){
            return null;
        }
        return seatMap.get(onlineUserMap.get(userId).getSeatNo());
    }

    public List<QmcsUserBO> getOtherPlayer(long userId){
        return onlineUserMap.values().stream().filter(u -> userId != u.getUserId()).collect(Collectors.toList());
    }

    public boolean emptyTable(){
        return  seatMap.size()  < QmcsConstantValue.SEAT_NUM;
    }

    public List<Integer> emptyPlayerSeat(){
        List<Integer> list = new ArrayList<>(QmcsConstantValue.SEAT_NUM);
        for (Integer i = 1; i<= QmcsConstantValue.SEAT_NUM; i++){
            if (null == seatMap.get(i)){
                list.add(i);
            }
        }
        return list;
    }

    public void clearOnlineUser(long userId){
        seatMap.remove(getSeatByUserId(userId));
        onlineUserMap.remove(userId);
    }

    public void exitGameTable(long userId){
        QmcsSeatManager seatManager = getSeatByUserId(userId);
        if (null == seatManager){
            return;
        }
        QmcsTableUtil.playerInoutMsg(this, seatManager,  0);
        onlineUserMap.remove(userId);
        seatMap.remove(seatManager.getSeatNo());
        stopGame();
    }

    public void stopGame(){
        if (onlineUserMap.isEmpty()){
            // TODO 停止捕鱼
            qmcsScheduleManager.stop();
            linkType = QmcsLinkType.Prepare.code();
        }

    }

    public void fishClear(){
        fishKeyId.set(0);
        //清楚鱼
        deadFish();
    }

    public void deadFish(){
        for (Integer k : qmcsMap.keySet()) {
            QmcsBO qmcsBO = qmcsMap.get(k);
            if (qmcsBO.getRemainStep()* QmcsConstantValue.STEP_TIME>= qmcsBO.getRuleStep()){
                //行走步长大于会定步长
                qmcsMap.remove(k);
            }
        }
    }

    public void lostConnection(long uid){

        GameSession session = onlineUserMap.get(uid).getGameSession();
        if (null==session||session.isWeakClose()){
            QmcsSeatManager seatManager = getSeatByUserId(uid);
            if (null == seatManager){
                return;
            }
            QmcsTableUtil.playerInoutMsg(this, seatManager,  0);
            onlineUserMap.remove(uid);
            seatMap.remove(seatManager.getSeatNo());
        }

    }

    public FishTableLog getFishTablelog(int fishType){
        FishTableLog fishTableLog = this.logMap.get(fishType);
        if (null==fishTableLog){
            fishTableLog = new FishTableLog();
            logMap.put(fishType,fishTableLog);
        }

        return fishTableLog;
    }


}
